package com.feihong.txgw.ui.fragment.order;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.adapter.base.BaseQuickAdapter;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.order.OrderAdapter;
import com.feihong.txgw.inter.contract.order.IOrderContract;
import com.feihong.txgw.json.user.AllOrderInfo;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.RefreshOrder;
import com.feihong.txgw.tx_precenter.OrderMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompatFragment;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;

/**
 * 全部订单
 */

public class OrderListFragment extends BaseMVPCompatFragment<IOrderContract.AbOrderMainPrecenter> implements
        IOrderContract.IOrderMainView, BaseQuickAdapter.RequestLoadMoreListener {

    public int state = 0;

    private OrderAdapter mOrderAdapter;
    @BindView(R.id.lv_order)
    RecyclerView lvOrder;
    @BindView(R.id.matereforder)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.lay_loading)
    RelativeLayout layLoading;
    /**
     * 没有订单情况下的交互页
     */
    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    /**
     * 没有订单时的图标
     */
    @BindView(R.id.null_data_layout_img)
    ImageView mNullDataImg;
    /**
     * 没有订单时的文字
     */
    @BindView(R.id.null_data_layout_txt)
    TextView mNullDataText;
    /**
     * 连接服务异常交互页
     */
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    /**
     * 连接服务器异常时的再次请求数据按钮
     */
    @BindView(R.id.re_query_data_layout)
    LinearLayout mRequeryDataBtn;

    /**
     * 当前列表是否有数据  如果没数据 则认为是第一次加载
     */
    private boolean isHasData = false;
    /**
     * 数据是否满一页
     */
    private boolean isFullData = false;

    private int mItemPosition;
    public static OrderListFragment newInstance(String tabName, int state) {
        OrderListFragment fragment = new OrderListFragment();
        fragment.tag = tabName;
        fragment.state = state;
        return fragment;
    }

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.fragment_order;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        //页面显示才能触发
        //绑定View
        initView();
        //绑定数据
        bindData();

    }

    @Override
    public void initView() {
        super.initView();
        EventBus.getDefault().register(this);

        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(223, 47, 47));
        mNullDataImg.setImageDrawable(getResources().getDrawable(R.mipmap.null_order_img));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(_mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lvOrder.setLayoutManager(linearLayoutManager);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isHasData = false;
                mPrecenter.loadOrderInfoFirst(state);
            }
        });
    }

    @Override
    public void bindData() {
        mOrderAdapter = new OrderAdapter(R.layout.layout_order_item);
        mOrderAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                mItemPosition = position;
                AllOrderInfo.DataBean.OrderPageBean orderInfo = (AllOrderInfo.DataBean.OrderPageBean) adapter.getItem(position);
                switch (view.getId()){
                    case R.id.cancle:
                        mPrecenter.onCancelBtnClick(orderInfo);
                        break;
                    case R.id.quren:
                        mPrecenter.onConfirmBtnClick(orderInfo);
                        break;
                    default:break;
                }

            }
        });
        mOrderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mItemPosition = position;
                AllOrderInfo.DataBean.OrderPageBean orderInfo = (AllOrderInfo.DataBean.OrderPageBean) adapter.getItem(position);
                mPrecenter.onItemClick(orderInfo,position);
            }
        });
        mOrderAdapter.setOnLoadMoreListener(this, lvOrder);
        lvOrder.setAdapter(mOrderAdapter);
        mRequeryDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mConnectErrorLayout.setVisibility(View.GONE);
                layLoading.setVisibility(View.VISIBLE);
                getData();
            }
        });
        getData();
    }

    private void getData() {
        mPrecenter.loadOrderInfo(state);
    }

    private void parsedData(List<AllOrderInfo.DataBean.OrderPageBean> orderInfo) {
        // 如果是第一次加载
        if(!isHasData){
            isHasData = !isHasData;
            mOrderAdapter.setNewData(orderInfo);
            mSwipeRefreshLayout.setVisibility(View.VISIBLE);
            mConnectErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
        }else {
            mOrderAdapter.addData(orderInfo);
        }
        mOrderAdapter.loadMoreComplete();
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public void loadDataComplated() {
        finishRefresh();
    }

    /**
     * 加载失败
     */
    @Override
    public void loadDataError() {
        finishRefresh();
        if (!isHasData) {
            mNullDataLayout.setVisibility(View.GONE);
            mSwipeRefreshLayout.setVisibility(View.GONE);
            mConnectErrorLayout.setVisibility(View.VISIBLE);
        }
        if(isFullData){
            mOrderAdapter.loadMoreFail();
        }else{
            mOrderAdapter.loadMoreEnd(false);
        }
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return OrderMainPrecenter.create();
    }

    /**
     * 加载订单列表成功返回
     * @param isFullPage 数据是否满一页
     * @param orderInfo
     */
    @Override
    public void loadOrderResult(boolean isFullPage, List<AllOrderInfo.DataBean.OrderPageBean> orderInfo) {
        this.isFullData = isFullPage;
        parsedData(orderInfo);
    }

    /**
     * 列表暂无数据
     * @param warningMsg  无数据时的提示
     */
    @Override
    public void loadEnd(String warningMsg) {
        if (!isHasData) {
            mOrderAdapter.loadMoreEnd();
            mNullDataLayout.setVisibility(View.VISIBLE);
            mSwipeRefreshLayout.setVisibility(View.GONE);
            mConnectErrorLayout.setVisibility(View.GONE);
            mNullDataText.setText(warningMsg);
        } else {
            mOrderAdapter.loadMoreEnd(!isFullData);
        }
    }

    @Override
    public void loadOtherError(String errorMsg) {
        showSystemToast(errorMsg);
        if (!isHasData) {
            mSwipeRefreshLayout.setVisibility(View.GONE);
            mConnectErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 刷新当前item
     * @param orderPageBean
     * @param isNotifyRemoveItem
     */
    @Override
    public void notifyItemChange(AllOrderInfo.DataBean.OrderPageBean orderPageBean, boolean isNotifyRemoveItem,String nullDataWanning) {
        if(isNotifyRemoveItem){
            boolean result = mOrderAdapter.removeItem(mItemPosition);
            if(result){
                isHasData = false;
                loadEnd(nullDataWanning);
            }
        }else {
            mOrderAdapter.notifyItemChanged(mItemPosition,orderPageBean);
        }
    }

    /**
     * 加载更多监听
     */
    @Override
    public void onLoadMoreRequested() {
        getData();
    }

    public interface OrderRefreshCallBack {
        public void refresh(int pagestate);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onRefreshOrder(RefreshOrder refreshOrder) {
//        if (state == 0 || state == 1 || state == 2) {
        ///全部列表，代付款列表，收货列表刷新就可以
        isFullData = false;
        isHasData = false;
        mPrecenter.loadOrderInfoFirst(state);
    }

    /**
     * 取消加载状态
     */
    private void finishRefresh() {
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
        if(layLoading.getVisibility() == View.VISIBLE){
            layLoading.setVisibility(View.GONE);
        }
    }
}
